<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.status"
        placeholder="状态"
        style="width: 120px"
        clearable
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="item in [{ value: -1, label: '全部' }, { value: 0, label: '待审核' }, { value: 1, label: '已审核' }, { value: -99, label: '已删除' }]"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-input
        v-model="listQuery.send_id"
        style="width: 200px; margin-left: 10px"
        placeholder="报单ID"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-input
        v-model="listQuery.user_id"
        placeholder="用户ID"
        style="width: 200px; margin-left: 10px"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-date-picker
        class="filter-item"
        v-model="listQuery.start"
        value-format="yyyy-MM-dd"
        type="date"
        @change="handleFilter"
        style="margin-left: 10px"
        placeholder="开始日期">
      </el-date-picker>
      -
      <el-date-picker
        class="filter-item"
        v-model="listQuery.end"
        type="date"
        @change="handleFilter"
        value-format="yyyy-MM-dd"
        placeholder="结束日期">
      </el-date-picker>
      <el-button
        v-waves
        type="primary"
        icon="el-icon-search"
        class="filter-item"
        style="margin-left: 10px;"
        @click="handleFilter"
      >搜 索</el-button>
      <el-button
        v-waves
        type="success"
        icon="el-icon-refresh"
        class="filter-item"
        style="margin-left: 10px;"
        @click="clearFilter"
      >清除筛选</el-button>
    </div>
    <div class="filter-container" v-if="false">
      <el-button
        v-waves
        type="success"
        icon="el-icon-download"
        class="filter-item"
        size="small"
        plain
        :loading="listLoading"
        @click="handleExport"
      >导出 Excel</el-button>
    </div>
    <div class="filter-container">
      <el-button
        v-waves
        type="danger"
        icon="el-icon-edit"
        class="filter-item"
        size="small"
        @click="handleBatchDelete"
      >批量审核</el-button>
      <el-button
        v-waves
        type="success"
        icon="el-icon-download"
        class="filter-item"
        size="small"
        plain
        :loading="listLoading"
        @click="handleExport"
      >导出 Excel</el-button>
    </div>
    <div class="filter-container" v-if="listQuery.user_id">
      <div class="text">
        用户: {{ listQuery.user_id }}, 总计报单: {{ data.count }}条, 数量: {{ data.quantity }}, 获取得积分: {{ data.score }}
      </div>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      :border="false"
      fit
      style="width: 100%;"
      @sort-change="sortChange"
      @selection-change="selectionChange"
    >
      <el-table-column
        type="selection"
        width="50"
      />
      <el-table-column sortable="custom" prop="id" label="ID" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="id" label="唯一ID" width="80">
        <template slot-scope="{row}">
          <span style="color: red">{{ +row.final_id > 0 ? row.final_id : row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="sn" label="报单ID">
        <template slot-scope="{row}">
          <span>{{ row.send_id }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="user_id" label="用户ID">
        <template slot-scope="{row}">
          <span>{{ row.user_id }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="amount" label="数量">
        <template slot-scope="{row}">
          <span>{{ +row.quantity }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="user_id" label="报单积分">
        <template slot-scope="{row}">
          <span>{{ row.temp_score }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="user_id" label="用户积分">
        <template slot-scope="{row}">
          <span style="color: red">{{ row.score }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" sortable="custom" prop="status" align="center">
        <template slot-scope="{row}">
          <span>{{ row.final | statusText }}</span>
        </template>
      </el-table-column>
      <el-table-column width="225" label="日志">
        <template slot-scope="{row}">
          <span v-if="row.log">
            {{ row.log.name }} 于 {{ row.log.time }} {{ row.log.text }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" sortable="custom" prop="create_time" width="160">
        <template slot-scope="{row:{create_time}}">
          <i class="el-icon-time" />
          <span style="margin-left: 5px">{{ create_time | timeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" sortable="custom" prop="update_time" width="160">
        <template slot-scope="{row}">
          <i class="el-icon-time" />
          <span style="margin-left: 5px">{{ row.update_time | timeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="220"
        fixed="right"
      >
        <template slot-scope="{ row }">
          <el-button type="success" size="mini" icon="el-icon-edit" @click="handleCheck(row)" v-if="+row.final === 0">
            审核
          </el-button>
          <el-button type="primary" size="mini" icon="el-icon-delete" @click="handleDelete(row)" v-if="+row.final === 0">
            删除
          </el-button>
          <!-- 只处理2024-10-31之前的 -->
          <template v-if="setTime(row)">
            <el-button type="default" size="mini" @click="has(row)" v-if="+row.final === 1">
              检测审核否
            </el-button>
            <el-button type="danger" size="mini" @click="set(row)" v-if="+row.final === 1">
              设为未审核
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="listQuery.total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      :page-sizes="[5, 10, 20, 50, 100]"
      @pagination="refresh"
    />
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import api from '@/api'
// import { baoDelete } from '@/api/modules/finance'

const initQuery = {
  page: 1,
  pageSize: 10,
  total: 0,
  sort: '-id'
}

export default {
  name: 'Pay',
  components: {
    Pagination
  },
  directives: { waves },
  filters: {
    timeFilter(time) {
      return time ? parseTime(time, '{m}-{d} {h}:{i}') : ''
    },
    statusText(status) {
      let str = '待审核'
      if (+status === 1) {
        str = '已审核'
      }
      if (+status === -99) {
        str = '已删除'
      }
      return str
    }
  },
  data() {
    return {
      listLoading: false,
      list: [],
      listQuery: {
      },
      defaultSort: {},
      payTotal: 0,
      selectionList: [],
      data: {
        a: 'aaaaa',
      }
    }
  },
  created() {
    // this.getPayTotal()
    this.parseQuery()
  },
  mounted() {
    this.getList()
  },
  methods: {
    // BUG时间, 只处理10-31之前的
    setTime(row) {
      const time = row.update_time
      const now = '2024-10-31 00:00:27'
      // console.log(time, now)
      if (new Date(time).getTime() > new Date(now).getTime()) {
        return false
      }
      return true
    },
    // 修复BUG
    has(row) {
      api.finance.baoHas({ ...row }).then(response => {
        const { data } = response
        this.$message.success({
          message: `该订单已经被审核过, 时间: ${data.time}, 获取积分: ${+data.score}`
        })
      })
    },
    set(row) {
      api.finance.baoSet({ ...row }).then(response => {
        this.$notify({
          title: '成功',
          message: response.message || '删除成功',
          type: 'success',
          duration: 2000
        })
        this.list.forEach(x => {
          if (x.id === row.id) {
            x.status = 0
            x.final = 0
          }
        })
      })
    },
    selectionChange(data) {
      this.selectionList = data
    },
    handleBatchDelete() {
      if (this.selectionList.length < 1) {
        this.$notify({
          type: 'error',
          title: '错误',
          message: '请选择要批量审核的数据',
          duration: 2000
        })
      } else {
        this.$confirm('您确定要批量审核这些吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const ids = this.selectionList.map(x => x.id)
          // console.log(ids)
          api.finance.baoCheckBatch({ ids }).then(response => {
            this.$notify({
              title: '成功',
              message: response.message || '删除成功',
              type: 'success',
              duration: 2000
            })
            this.listQuery.d = new Date().getTime()
            this.handleFilter()
          })
        })
      }
    },
    handleDelete(row) {
      this.$confirm('您确定要通过删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.finance.baoDelete({ id: row.id }).then(response => {
          this.$message({
            message: response.message || '操作成功',
            type: 'success'
          })
          this.list.forEach(x => {
            if (x.id === row.id) {
              x.status = -99
              x.final = -99
            }
          })
        })
      }).catch(() => {})
    },
    handleCheck(row) {
      this.$confirm('您确定要通过审核吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.finance.baoCheck({ id: row.id }).then(response => {
          this.$message({
            message: response.message || '操作成功',
            type: 'success'
          })
          this.list.forEach(x => {
            if (x.id === row.id) {
              x.final = 1
            }
          })
        })
      }).catch(() => {})
    },
    getList() {
      this.listLoading = true
      api.finance.baoList({ ...this.listQuery }).then(response => {
        const { data } = response
        this.list = data.list
        this.listQuery.total = +data.totalCount
        this.data = data.data
        this.listLoading = false
      }).finally(() => {
        this.listLoading = false
      })
    },
    /**
     * 排序
     * @param data
     */
    sortChange(data) {
      const sortBy = (prop, order) => {
        if (prop && order === 'ascending') {
          this.listQuery.sort = `+${prop}`
        } else if (prop && order === 'descending') {
          this.listQuery.sort = `-${prop}`
        } else {
          this.listQuery.sort = ''
        }
      }
      const { prop, order } = data
      sortBy(prop, order)
      this.handleFilter()
    },
    /**
     * 刷新
     */
    refresh() {
      this.$router.push({
        path: '/order/bao',
        query: this.listQuery
      })
    },
    /**
     * 过滤(筛选)
     */
    handleFilter() {
      // this.listQuery.page = 1
      this.refresh()
    },
    /**
     * 清除筛选
     */
    clearFilter() {
      this.listQuery = Object.assign({}, initQuery)
      this.defaultSort = {}
      this.refresh()
    },
    /**
     * 处理筛选条件
     */
    parseQuery() {
      const query = Object.assign({}, this.$route.query)
      let sort = '-id'
      this.listQuery = Object.assign({}, { ...initQuery, sort })
      if (Object.keys(query).length > 0) {
        // 注意这里的类型转换
        query.page && (query.page = +query.page)
        query.pageSize && (query.pageSize = +query.pageSize)
        query.total && (query.total = +query.total)
        query.status && (query.status = +query.status)
        query.sort && (sort = query.sort)
      }
      const sortSymbol = sort[0]
      const sortColumn = sort.slice(1, sort.length)
      this.defaultSort = {
        prop: sortColumn,
        order: sortSymbol === '+' ? 'ascending' : 'descending'
      }
      this.listQuery = { ...this.listQuery, ...query }
    },
    /**
     * 导出
     */
    async handleExport() {
      const formatJson = (filterVal, jsonData) => {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'status') {
            return this.$options.filters['statusText'](v[j])
          }
          if (j === 'log') {
            // console.log(v)
            if (v['log']) {
              return `${v['log'].name} 于 ${v['log'].time} ${v['log'].text}`
            }
            return ''
          }
          return v[j]
        }))
      }
      this.listLoading = true
      const response = await api.finance.baoList({ ...this.listQuery, export: true })
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['ID', '唯一ID', '报单ID', '用户ID', '报单积分', '用户积分', '状态', '日志', '创建时间', '操作时间']
        const filterVal = ['id', 'final_id', 'send_id', 'user_id', 'temp_score', 'score', 'status', 'log', 'create_time', 'update_time']
        const list = response.data
        const data = formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '报单列表'
        })
      })
      this.listLoading = false
    },
    /**
     * 排序设置
     */
    handleSort(row) {
      api.category.changeSort({ ...row }).then(response => {
        this.$notify({
          title: '成功',
          message: response.message || '设置成功',
          type: 'success',
          duration: 2000
        })
      })
    }
  },
  /**
   * 刷新
   * @param to
   * @param from
   * @param next
   */
  beforeRouteUpdate(to, from, next) {
    if (to.path === from.path) {
      const newQuery = Object.assign({}, to.query)
      const oldQuery = Object.assign({}, from.query)
      if (JSON.stringify(newQuery) !== JSON.stringify(oldQuery)) {
        this.getList()
      }
    }
    next()
  }
}
</script>

<style scoped lang="scss">
.text {
  color: red;
}
</style>
